

from config import *
import requests,json

class Helper( object ):

    def __init__(self):

        pass

    # 记录错误日志
    @staticmethod
    def writeErrorLog( data):

        import os,datetime

        filename = str(datetime.date.today()).replace('-','')

        errorLog = '错误日志'

        data = json.dumps(data,ensure_ascii=False)

        if not os.path.exists(errorLog):

            os.mkdir( errorLog )

        with open('./{0}/{1}.txt'.format(errorLog,filename),mode='a') as f:

            f.write('{0}\n'.format(data))

        print('拼多多内部请求参数错误&&服务器错误,记录日志成功')

        f.close()

    # 测试初次请求是否封号
    @staticmethod
    def testCaseReqeust(  arguments = None ):

        import requests,json

        header['cookie'] = arguments['cookie']

        data = {"pageSize":10,"pageNo":1,"status":0,"startTime":Helper.genTimeInterval()['start_time'],"endTime":Helper.genTimeInterval()['end_time']}

        resp = lambda : requests.post( domain_url['comments_url'],headers=header,data=json.dumps( data ))

        r = resp()

        # print( r.json())
        # 判断cookie是否过期
        if r.status_code == 200 and "会话已过期" in json.dumps( r.json(),ensure_ascii=False):

            error = dict(errorCode=r.json()['error_code'],errorMsg=r.json()['error_msg'])

            # # 判断是否为验证行为
            # if 'action' not in arguments:

            data = {

                "zhanghao": arguments["account"],
                "dianpuming": arguments["shop_name"],
                "Cookie": ""
            }

            data = json.dumps(data)

            # Helper.returnCookieTask(data)

                # return False
            return error


        # IP被封号
        elif r.status_code == 200 and not r.json()['result']:

            error=dict( errorCode=r.json()['errorCode'],errorMsg='账号被封禁')

            print( error )

            return False

        # 正常情况
        else:

            return True

    # 生成三十天之内的时间戳
    @staticmethod
    def genTimeInterval():

        import time

        data = {}

        end_time = int( time.time())

        start_time = int( end_time - (30 * 24 * 3600 ))

        data["start_time"] = start_time
        data["end_time"] = end_time

        return data

    # 日期转换时间戳
    @staticmethod
    def changeTimeStamp( date=None ):

        import time

        timeArray = time.strptime(date, "%Y-%m-%d %H:%M:%S")

        timeStamp = int(time.mktime(timeArray))

        return timeStamp

    # 返回评价任务
    @staticmethod
    def returnCommentTask( data ):

        r = requests.post(url=domain_url['return_comments_url'],data={"Post_Data":data})

        print(r.text)

        if r.status_code == 200 :

            print('任务状态回传成功')

        else:

            print('任务状态回传失败')

    # 更新cookie
    @staticmethod
    def returnCookieTask( data ):

        r = requests.post( url=domain_url['return_cookie_url'],data={"Post_Data":data})


        if r.status_code == 200 and len(r.text) == 1 :

            print('COOKIE信息重置成功')

        else:

            print('COOKIE信息重置失败')

    #获取cookie进行验证
    @staticmethod
    def verifyAccess():

        from urllib.parse import unquote

        try:

            r = requests.get(url=domain_url['check_status_url'])

            print( r.text)

            if r.status_code == 200 and 'details' not in r.json():

               print('服务端错误,未能领取到COOKE信息')

            details = r.json()['details']
            res = {

                'shop_name':details['shop_name'],
                'account':details['account'],
                'cookie':unquote(details['cookie'])

            }

            result = Helper.testCaseReqeust(res)

            return result

        except Exception as e:

            print('服务端代码错误,返回400错误信息')


if __name__ == '__main__':

    # data = json.dumps({
    #     "caijiwancheng": [{
    #         "task_id": "223333",
    #         "state": "6",
    #         "shop_id": "173"
    #     }]
    # })
    #
    #
    # from urllib.parse import unquote
    # task = {'id': '223333', "shop_name": "Fans梵兮服饰店", "account": "fans", 'type': '8', 'shop_id': '173',
    #         't_start_time': '2019-06-29 04:00:00', 't_end_time': '2019-08-29 04:15:00', 'details_type': None,
    #         'cookie': unquote('api_uid%3DrBQR7F2BzbAGSVa7ZHedAg%3D%3D%3B_nano_fp%3DXpdjl0mJnqCbX5EaXo_UceBlbg9SLFR_vdbo_pwe%3BPASS_ID%3D1-5ADBRqfY4%2FWqn61HT%2FcnJv2Qa1ns40GeXfsxinkmLJBrozzdT6S5B8XDaNx23Ur6bb4gFOGwsJUAmfu4aWPQng_982621149_43197961')}

    task = {"id": "26574", "shop_id": "171", "type": "8", "task_id": "26573", "tasktime": "2019-09-21 16:46:01", "state": null, "cookie": "api_uid=rBQhGl2EmlRKFiltICFmAg==;_nano_fp=Xpdjl0U8XpXYnpTyn9_1gURbQLnYJ7VAon9l~V~5;PASS_ID=1-bOli+r9oLXAMutMz6jCflQxvrW7iaTcDjYQfIfoghCklUGtbQ2SOdOuytcTHEmYA/onJ6Z3xnqBF9d44oKRFZQ_1953223_44011247", "account": "欣美儿服饰dsr1", "shop_name": "欣美儿服饰"}



